/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
package openbackup.data.access.client.sdk.api.config.achive;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Getter;
import lombok.Setter;
import openbackup.system.base.common.exception.LegoCheckedException;

import java.util.Optional;

/**
 * DME Response
 *
 * @param <T> template type
 */
@Getter
@Setter
public class DmeResponse<T> {
    @JsonProperty("Data")
    private T data;

    @JsonProperty("Error")
    private DmeResponseError error;

    /**
     * get checked data
     *
     * @return checked data
     */
    @JsonIgnore
    public T getCheckedData() {
        checkData();
        return data;
    }

    /**
     * check data
     */
    public void checkData() {
        Optional<LegoCheckedException> exception = getExceptionIfError();
        if (exception.isPresent()) {
            throw exception.get();
        }
    }

    /**
     * get exception if error
     *
     * @return exception
     */
    public Optional<LegoCheckedException> getExceptionIfError() {
        if (error != null && error.getCode() > 0) {
            return Optional.of(new LegoCheckedException(error.getCode(), error.getDetailParams()));
        }
        return Optional.empty();
    }
}
